/*
 * @Description: 这个文件用于加密， 通过随机向量和秘钥双加密，即便秘钥泄漏也有随机向量进行加密保证
 * @Autor: tao wenbo 2419421809@qq.com
 * @Date: 2023-05-16 15:41:04
 * @LastEditors: tao wenbo 2419421809@qq.com
 * @LastEditTime: 2023-05-16 16:36:56
 */

import crypto from "crypto";
const secret = Buffer.from('sdwea32dw39ef21i')
/**
 * @description: 加密和解密
 * @return {*}
 * @author: tao wenbo 2419421809@qq.com
 */
const CryptoUtil = function () {
    // 准备iv，随机向量
    const iv = Buffer.from(Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8));
    // 加密算法
    const algorithm = "aes-128-cbc"
    return {
        encrypt(str: string) {
            const cry = crypto.createCipheriv( algorithm, secret, iv )
            let result = cry.update( str, "utf-8", 'hex' )
            result += cry.final("hex")
            return result
        },
        decrypt(str: string) {
            const decry = crypto.createDecipheriv( algorithm, secret, iv )
            let result = decry.update( str, 'hex', 'utf-8' )
            result += decry.final("utf-8")
            return result
        },
    };
};

export default CryptoUtil()